//
//  MemberListViewController.swift
//  WNLockDemo
//
//  Created by 裴威 on 03/09/2018.
//  Copyright © 2018 wunu. All rights reserved.
//

import UIKit
import PKHUD
import SwiftyJSON

protocol MemberListCellItem {
}
extension WNLockAuthorizedMember: MemberListCellItem {
    
}
extension WNLockTemporaryMember: MemberListCellItem {}

class MemberListViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    var lock: WNLockModel!
    var data: [[MemberListCellItem]] = [] {
        didSet {
            tableView.reloadData()
        }
    }
    var isOwner: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "锁成员"
        configureNavigationBarBack()
        fetchData()
    }
    
    private func fetchData() {
        if lock == nil {
            return
        }
        WNLockApi.lockMember(lockId: lock.id ?? 0).execute { (result: FxResponseResult<WNLockMemberListModel>) in
            switch result {
            case .success(let listModel):
                self.data.removeAll()
                self.data = [listModel.lockMembers ?? [], listModel.tempMembers ?? []]
                self.isOwner = listModel.isOwner ?? false
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

// MARK: - UITableViewDataSource
extension MemberListViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data[section].count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "AuthorizedMemberCell", for: indexPath) as! AuthorizedMemberTableViewCell
            let model = data[indexPath.section][indexPath.row] as! WNLockAuthorizedMember
            cell.avatarImageView.kf.setImage(with: URL(string: model.photo ?? ""), placeholder: UIImage(named: "default_head_image"))
            cell.nameLabel.text = model.name
            var roleText = ""
            switch model.group {
            case 0?:
                roleText = "管理员"
            case 1?:
                roleText = "家庭成员"
            case 2?:
                roleText = "保姆"
            case 3?:
                roleText = "钟点工"
            default:
                roleText = ""
            }
            cell.memberRoleLabel.text = roleText
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TemporaryMemberCell", for: indexPath) as! TemporaryMemberTableViewCell
            let model = data[indexPath.section][indexPath.row] as! WNLockTemporaryMember
            cell.avatarImageView.kf.setImage(with: URL(string: model.photo ?? ""), placeholder: UIImage(named: "default_head_image"))
            cell.nameLabel.text = model.name
            cell.tempKeyCodeLabel.text =  "\(model.tempKey ?? 0)"
            cell.tempKeyLeftCountLabel.text = "\(model.validCount ?? 0)次"
            cell.validStatusLabel.text = model.state!  == 2 ? "已过期" : ""
            return cell
        }
    }
}

extension MemberListViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: false)
        if !isOwner {
            HUD.flash(.label("您不是管理员，无法进行成员操作"), delay: 1.5)
            return
        }
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        // 临时密钥
        if indexPath.section == 1 {
            let item = data[indexPath.section][indexPath.row] as! WNLockTemporaryMember
            
            let deleteAction = UIAlertAction(title: "删除", style: .default) { _ in
                self.handleTempKey(id: item.id ?? 0, state: 0, isDelete: true)
            }
            let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in }
            alertController.addAction(deleteAction)
            alertController.addAction(cancelAction)
            
        } else {
            let item = data[indexPath.section][indexPath.row] as! WNLockAuthorizedMember
            if item.state ?? 0 == 0 {
                //未启用
                let startAction = UIAlertAction(title: "启用", style: .default) { _ in
                    self.handleMembers(id: item.id ?? 0, state: 1, isDelete: false)
                }
                let deleteAction = UIAlertAction(title: "删除", style: .default) { _ in
                    self.handleMembers(id: item.id ?? 0, state: 0, isDelete: true)
                }
                let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
                    
                }
                alertController.addAction(startAction)
                alertController.addAction(deleteAction)
                alertController.addAction(cancelAction)
            } else {
                let startAction = UIAlertAction(title: "停用", style: .default) { _ in
                    self.handleMembers(id: item.id ?? 0, state: 0, isDelete: false)
                }
                let deleteAction = UIAlertAction(title: "删除", style: .default) { _ in
                    self.handleMembers(id: item.id ?? 0, state: 0, isDelete: true)
                }
                let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in }
                alertController.addAction(startAction)
                alertController.addAction(deleteAction)
                alertController.addAction(cancelAction)
            }
            
        }
        present(alertController, animated: true, completion: nil)
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
        headerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        let label1 = UILabel(frame: CGRect(x: 20 ,y: 8, width:0, height: 0))
        label1.text = section == 0 ? "认证成员" : "临时密钥"
        label1.font = UIFont.systemFont(ofSize: 14)
        label1.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        label1.sizeToFit()
        headerView.addSubview(label1)
        let label2 = UILabel(frame: CGRect.zero)
        label2.text = section == 0 ? "包括管理员，家庭成员，保姆，钟点工等" : "仅限管理员，家庭成员可授权"
        label2.textColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
        label2.font = UIFont.systemFont(ofSize: 12)
        label2.sizeToFit()
        label2.frame = CGRect(x: label1.bounds.maxX + 30, y: 10, width: label2.bounds.width, height: label2.bounds.height)
        headerView.addSubview(label2)
        return headerView
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

extension MemberListViewController {
    fileprivate func handleMembers(id: Int, state: Int, isDelete: Bool) {
        WNLockApi.changeLockMember(memberId: id, state: state, isDelete: isDelete).execute { result in
            switch result {
            case .success(let json):
                if json["code"].intValue == 200 {
                    HUD.flash(.label("操作成功"), delay: 1.5)
                    self.fetchData()
                } else {
                    HUD.flash(.label("操作失败"), delay: 1.5)
                }
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
    fileprivate func handleTempKey(id: Int, state: Int, isDelete: Bool) {
        WNLockApi.changeTempKey(memberId: id, state: state, isDelete: isDelete).execute { result in
            switch result {
            case .success(let json):
                if json["code"].intValue == 200 {
                    HUD.flash(.label("操作成功"), delay: 1.5)
                    self.fetchData()
                } else {
                    HUD.flash(.label("操作失败"), delay: 1.5)
                }
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
}
